package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Provider;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>APP实名认证信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResultVo pageList(ApUserRealnamePageRequestDto dto) {
        //1.设置分页参数
        Page<ApUserRealname> pageInfo = new Page<>(dto.getPage(), dto.getSize());
        //2.构建查询条件
        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());
        //3.查询
        page(pageInfo, lqw);

        //4.构建分页查询结果返回
        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());


    }

    /**
     * 审核通过
     * @param paramMap
     */
    @Override
    public void authPass(Map<String, Object> paramMap) {
        //============实名认证信息表=================

        // 获取参数信息
        Integer id = (Integer) paramMap.get("id");
        //状态判断
        // 通过id查询
        ApUserRealname apUserRealname = getById(id);

        //数据不存在或状态不为1，报错
        if (null == apUserRealname || apUserRealname.getStatus() != 1) {
            throw new LeadNewsException("状态不正确或者数据不存在");
        }

        //更新
        //创建updatePojo
        ApUserRealname updatePojo = new ApUserRealname();
        //设置id与更新的字段新值
        updatePojo.setId(id.longValue());
        updatePojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        updatePojo.setUpdatedTime(LocalDateTime.now());
        //执行更新
        updateById(updatePojo);

        //============用户信息表=================
        Long apUserId = apUserRealname.getUserId();
        //创建updatePojo
        ApUser updateApUser = new ApUser();
        //设置id为上面查询到的用户id
        updateApUser.setId(apUserId);
        //设置flag， is_identity_authentication
        updateApUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        updateApUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        //执行更新
        apUserMapper.updateById(updateApUser);

        //============自媒体微服 自媒体用户表=================
        //远程调用
        //1.通过ap_user.id查询自媒体用户表
        ResultVo<WmUser> getByApUserIdResult = wmUserFeign.getByApUserId(apUserId);
        //如果远程调用失败，抛异常
        if (!getByApUserIdResult.isSuccess()) {
            log.error("用户实名认证::远程调用自媒体查询失败:{},{}", apUserId, getByApUserIdResult.getErrorMessage());
            throw new LeadNewsException("查询自媒体用户信息失败！");
        }

        //2.查询用户表信息
        ApUser apUserInfo = apUserMapper.selectById(apUserId);

        //2.如果不存在，则远程调用添加自媒体账号
        WmUser wmUser = getByApUserIdResult.getData();
        if (null == wmUser) {
            //远程调用添加自媒体账号
            wmUser = adWmUser(apUserInfo);
        }
        //自媒体用户 id
        Long wmUserId = wmUser.getId();
        //============文章微服 作者表=================
        //1. 远程调用 通过ap_user.id, 自媒体用户的id 查询文章微服作者表getByApUserIdAndWmUserId
        ResultVo<ApAuthor> getAuthorResult = apAuthorFeign.getByApUserIdWmUserId(apUserId, wmUserId);
        //1.1 解析结果
        if (!getAuthorResult.isSuccess()) {
            log.error("用户实名认证::远程调用文章微服查询失败:{},{},{}", apUserId, wmUserId, getAuthorResult.getErrorMessage());
            // 远程调用失败了
            throw new LeadNewsException("查询作者信息失败!");
        }
        //2. 如果不存在，则远程调用添加作者
        ApAuthor author = getAuthorResult.getData();
        if (null == author) {
            //则远程调用添加作者
            addAuthor(apUserInfo, wmUserId);
        }
    }

    /**
     * 审核 驳回
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //1. 获取参数
        Integer id = (Integer) paramMap.get("id");
        String reason = (String) paramMap.get("msg");
        //2. 创建更新的pojo
        ApUserRealname updatePojo = new ApUserRealname();
        updatePojo.setId(id.longValue());
        updatePojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        updatePojo.setReason(reason);
        updatePojo.setUpdatedTime(LocalDateTime.now());
        //3. 执行更新
        updateById(updatePojo);
    }
    /**
     * 远程调用添加作者
     * @param apUserInfo
     * @param wmUserId
     */
    private void addAuthor(ApUser apUserInfo, Long wmUserId) {
        //1. 构建作者的pojo
        ApAuthor author = new ApAuthor();
        author.setWmUserId(wmUserId);
        author.setName(apUserInfo.getName());
        author.setUserId(apUserInfo.getId());
        author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
        author.setCreatedTime(LocalDateTime.now());
        //2. 远程调用添加作者
        ResultVo resultVo = apAuthorFeign.add(author);
        //3. 解析结果
        if(!resultVo.isSuccess()){
            log.error("用户实名认证::远程调用添加作者失败:{},{}",apUserInfo.getId(),wmUserId,resultVo.getErrorMessage());
            throw new LeadNewsException("添加作者失败!");
        }
    }

    /**
     * 远程调用添加自媒体账号
     * @param apUserInfo
     * @return
     */
    private WmUser adWmUser(ApUser apUserInfo) {
        //1.构建自媒体账号信息
        WmUser pojo = new WmUser();
        Long apUserId = apUserInfo.getId();

        //3.复制用户表信息到自媒体账号中
        BeanUtils.copyProperties(apUserInfo, pojo);

        //4.补充自媒体信息
        pojo.setId(null);//由系统生成id
        pojo.setApUserId(apUserId);
        pojo.setNickname(apUserInfo.getName());
        pojo.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
        pojo.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
        pojo.setScore(0);//设为0分，补充 常量
        pojo.setCreatedTime(LocalDateTime.now());

        //5.远程调用添加自媒体账号
        ResultVo<WmUser> addResult = wmUserFeign.add(pojo);
        //6.解析远程调用后的结果
        if (!addResult.isSuccess()) {
            log.error("用户实名认证::远程调用自媒体添加账号失败:{},{}", apUserId, addResult.getErrorMessage());
            throw new LeadNewsException("添加自媒体账号失败！");
        }
        //7.返回数据
        return addResult.getData();
    }
}
